package com.web.controller;

import com.web.pojo.Result;
import com.web.pojo.User;
import com.web.service.UserService;
import com.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author web
 * @version 1.0
 * @date 2024/04/10 22:27
 */
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping
    public Result login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) {
        log.info("员工登录: {}", user);

        // 获取用户输入的验证码
        String checkCode = user.getCheckCode();
        // 获取程序生成的验证码
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");
        session.setAttribute("username", user.getUsername());
        session.setAttribute("password", user.getPassword());

        // 验证码比对
        if (checkCode != null && !checkCodeGen.equalsIgnoreCase(checkCode)) {
            // 不允许登录
            return Result.error("验证码有误");
        }

        // 获取复选框的数据
        String remember = user.getRemember();
        System.out.println(remember);

        // 调用service 查询
        User e = userService.login(user);
        System.out.println(user);

        // 判断
        if (e != null) {
            // 登录成功，生成令牌，下发令牌
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", e.getId());
            claims.put("username", e.getUsername());
            claims.put("password", e.getPassword());
            String jwt = JwtUtils.generateJwt(claims); // jwt令牌包含了当前登录的员工信息

            // 将登录成功后的user对象，存储到session
            session.invalidate();
            session = request.getSession();
            session.setAttribute("user", e);

            //判断是否勾选记住我
            if ("on".equals(remember)/*字符串写前面可以避免空指针异常*/) {
                log.info("勾选了记住我");
                Cookie c_username = new Cookie("username", e.getUsername());
                Cookie c_password = new Cookie("password", e.getPassword());
                c_username.setMaxAge(60 * 60 * 24 * 7);
                c_password.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(c_username);
                response.addCookie(c_password);
            } else {
                // 没勾选就删除cookie
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if ("username".equals(cookie.getName())) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                    if ("password".equals(cookie.getName())) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
            }
            return Result.success(jwt);

        } else {
            // 登录失败，返回错误信息
            return Result.error("用户名或密码错误");
        }
    }
}
